<template>
  <ElDialog
    v-model="visible"
    title="操作"
    width="600px"
    top="4vh"
    :close-on-click-modal="false"
    @open="handleOpen"
    @close="handleClose"
  >
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right">
      <ElRow :gutter="20">
        <ElCol :span="24">
          <ElFormItem label="操作类型" prop="serveFlag">
            <ElRadioGroup v-model="form.type" @change="changeTypeEvent">
              <ElRadio :value="1">入库</ElRadio>
              <ElRadio :value="2">出库</ElRadio>
              <ElRadio :value="3">修改库存</ElRadio>
              <ElRadio :value="4">上/下架</ElRadio>
              <ElRadio :value="5">删除</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>
        <ElCol :span="24" v-if="form.type === 1 || form.type === 2">
          <ElFormItem :label="`${form.type === 1 ? '入库' : '出库'}数量`" prop="num">
            <ElInputNumber
              v-model="form.num"
              :min="1"
              :max="99999"
              :placeholder="`请输入${form.type === 1 ? '入库' : '出库'}数量`"
              style="width: 100%"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24" v-if="form.type === 3">
          <ElFormItem label="修改数量" prop="shopStockNum">
            <el-radio-group v-model="stockRadio" style="margin-right: 10px">
              <el-radio-button label="增加" :value="1" />
              <el-radio-button label="减少" :value="2" />
            </el-radio-group>
            <el-input-number
              v-model="form.shopStockNum"
              :min="1"
              :max="99999"
              controls-position="right"
            />
            <div style="margin-top: 4px; color: red"
              >当前库存：{{ actData.shopStockNum }} / 调整后库存：{{ adjustStockNum }}</div
            >
          </ElFormItem>
        </ElCol>
        <ElCol :span="24" v-if="form.type === 4">
          <ElFormItem label="上架状态" prop="shopUpFlag">
            <ElSelect v-model="form.shopUpFlag" placeholder="请选择上架状态">
              <ElOption label="下架" :value="1" />
              <ElOption label="上架" :value="2" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">取消</ElButton>
        <ElButton type="primary" :loading="loading" @click="handleSubmit"> 确定 </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  import type { FormInstance, FormRules } from 'element-plus'
  import {
    scoGoodsShopUpdateUpUsingPost,
    scoGoodsShopOutStockAndRemoveUsingPost,
    scoGoodsShopInStockUsingPost,
    scoGoodsShopOutStockUsingPost,
    scoGoodsShopUpdateStockUsingPost
  } from '@/api/scOjifenshangpinduihuandi'
  // 类型定义
  interface Props {
    modelValue: boolean
    actData?: any | null
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const adjustStockNum = computed(() => {
    let num = 0
    if (stockRadio.value === 1) {
      num = form.shopStockNum + Number(props.actData?.shopStockNum)
    } else {
      num = Number(props.actData?.shopStockNum) - form.shopStockNum
    }
    return num
  })

  // Props 和 Emits
  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    actData: undefined
  })
  const emit = defineEmits<Emits>()

  // 响应式数据
  const formRef = ref<FormInstance>()

  const loading = ref(false)

  const form = reactive({
    type: 1,
    num: 0,
    shopStockNum: 1,
    shopUpFlag: 2
  })
  const stockRadio = ref(1)
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  // 表单验证规则
  const rules: FormRules = {
    num: [{ required: true, message: '请输入数量', trigger: 'blur' }],
    shopStockNum: [{ required: true, message: '请输入数量', trigger: 'blur' }],
    shopUpFlag: [{ required: form.type === 3, message: '请选择上架状态', trigger: 'change' }]
  }

  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      if (loading.value) return
      loading.value = true
      switch (form.type) {
        case 1: // 入库
          await scoGoodsShopInStockUsingPost({
            body: {
              shopId: route.query.id,
              goodsId: props.actData?.scoGoodsVo?.id,
              shopStockNum: form.num
            }
          })
          break
        case 2: // 出库
          await scoGoodsShopOutStockUsingPost({
            body: {
              shopId: route.query.id,
              goodsId: props.actData?.scoGoodsVo?.id,
              shopStockNum: form.num
            }
          })
          break
        case 3: // 修改库存
          await scoGoodsShopUpdateStockUsingPost({
            body: {
              shopId: route.query.id,
              goodsId: props.actData?.scoGoodsVo?.id,
              shopStockNum: stockRadio.value === 1 ? form.shopStockNum : -form.shopStockNum
            }
          })
          break
        case 4: // 上/下架
          await scoGoodsShopUpdateUpUsingPost({
            body: {
              shopId: route.query.id,
              goodsId: props.actData?.scoGoodsVo?.id,
              shopUpFlag: form.shopUpFlag
            }
          })
          break
        case 5: // 删除
          await scoGoodsShopOutStockAndRemoveUsingPost({
            body: {
              shopId: route.query.id,
              goodsId: props.actData?.scoGoodsVo?.id
            }
          })
          break
        default:
          throw new Error('未知操作类型')
      }

      formRef.value?.resetFields()
      ElMessage.success('操作成功')
      emit('success')
    } catch (error: any) {
      console.log(error)
      ElMessage.error('操作失败')
    } finally {
      loading.value = false
    }
  }

  const changeTypeEvent = () => {
    form.num = 0
    formRef.value?.resetFields()
  }

  const handleOpen = () => {
    form.type = 1
    form.num = 0
    form.shopUpFlag = props.actData?.shopUpFlag
    formRef.value?.resetFields()
  }

  const handleClose = () => {
    formRef.value?.resetFields()
    nextTick(() => {
      visible.value = false
    })
  }
</script>

<style lang="scss" scoped>
  :deep(.service-item) {
    .el-form-item__content {
      .el-form-item__error {
        margin-top: -12px;
        margin-left: 46px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }
</style>
